<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
namespace app\timer\service\sharp;

use app\timer\library\Tools;
use app\common\service\BaseService;
use app\timer\model\Order as OrderModel;
use app\common\service\Order as OrderService;
use app\common\enum\order\OrderStatus as OrderStatusEnum;
use app\common\enum\order\OrderSource as OrderSourceEnum;
use app\common\library\helper;

/**
 * 服务类：秒杀订单模块
 * Class Order
 * @package app\timer\service\sharp
 */
class Order extends BaseService
{
    /**
     * 未支付订单自动关闭
     * @param int $storeId
     * @param int $closeMinute
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function closeEvent(int $storeId, int $closeMinute)
    {
        // 截止时间
        $deadlineTime = time() - ($closeMinute * 60);
        // 查询截止时间未支付的订单
        $model = new OrderModel;
        $list = $model->getListByClose($storeId, $deadlineTime, OrderSourceEnum::SHARP);
        // 订单ID集
        $orderIds = helper::getArrayColumn($list, 'order_id');
        if (!empty($orderIds)) {
            // 取消订单事件
            foreach ($list as $order) {
                OrderService::cancelEvent($order);
            }
            // 批量更新订单状态为已取消
            $model->onBatchUpdate($orderIds, ['order_status' => OrderStatusEnum::CANCELLED]);
        }
        // 记录日志
        Tools::taskLogs('SharpOrder', 'closeEvent', [
            'storeId' => $storeId,
            'closeMinute' => $closeMinute,
            'deadlineTime' => $deadlineTime,
            'orderIds' => helper::jsonEncode($orderIds)
        ]);
    }
}